package com.example.redissontest.service;

import com.example.redissontest.util.RedissonLockUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author rfuser
 */
@Service
@Slf4j
public class MyService {
    @Resource
    private RedissonLockUtil redissonLockUtil;


    public void manuallyAcquireLock() throws Exception {
        String lockKey = "myLock";
        if (redissonLockUtil.tryLock(lockKey,1,3, TimeUnit.SECONDS)) {
            try {
                // manipulate protected state
                doSomething();
            } finally {
                redissonLockUtil.unlock(lockKey);
            }
        } else {
            doNothing();
        }
    }

    public void doSomething() throws Exception {
        Thread.sleep(3000);
        System.out.println("do something");
    }

    public void doNothing() throws Exception {
        Thread.sleep(3000);
        System.out.println("do nothing");
    }

    public String hello(String name) throws Exception {
        Thread.sleep(3000);
        log.info("hello {}", name);
        return "hello "+ name;
    }
}
